import React from "react";
import { inject, observer } from "mobx-react";
import { observable } from 'mobx';
import { Button, message, Tabs, Icon, Row, Col } from "antd";
import {
  WeaDialog, WeaQrcode, WeaInput, WeaTextarea,
  WeaInputNumber, WeaCheckbox, WeaTimePicker,
  WeaDatePicker, WeaTimeRangePicker, WeaLocaleProvider
} from "ecCom";
import CopyToClipboard from 'react-copy-to-clipboard';
import "./index.less";
import _ from "lodash";
const getLabel = WeaLocaleProvider.getLabel;

const TabPane = Tabs.TabPane;

@inject('routing', 'edcPublishStore', 'edcAppStore', 'edcAppDesignerStore')
@observer
export default class PublishingDialog extends React.Component {
  @observable saving = false;
  @observable error = '';
  @observable selectKey = '1';
  @observable wxTypeSelectKey = '1';

  constructor(props) {
    super(props);
    this.store = this.props.edcPublishStore;
    this.onOk = this.onOk.bind(this);
    this.setWxVisible = this.setWxVisible.bind(this);
  }

  componentWillMount() {
    const { getSetInfo, getSubmissionAuthority, getFillinFrequency } = this.store;
    const { appid } = this.props;

    if(appid) {
      getSetInfo(appid);
      getSubmissionAuthority();
      getFillinFrequency();
    }
  }

  componentWillRecieveProps(nextProps) {
    const { getSetInfo } = this.store;

    if(nextProps.appid !== this.props.appid) {
      getSetInfo(nextProps.appid);
    }
  }

  onOk() {
    const { setUpdate } = this.store;
    const { onCancel } = this.props

    this.saving = true;

    if(this.validate()) {
      setUpdate().then(() => {
        this.saving = false;
        message.success(getLabel('502234', '设置成功'));
        onCancel();
      });
    } else {
      message.error(this.error);
      this.saving = false;
    }
  }

  validate() {
    const { publishSettings, wechatTypeInfo } = this.store;
    let isValidate = true;

    if(publishSettings.fillinEnabled.toString() === 'false') {
      return isValidate;
    }
    if(publishSettings.timeRangeEnabled.toString() === 'true') {
      if(publishSettings.startTime.length < 7 || publishSettings.endTime.length < 7) {
        isValidate = false;
        this.error = getLabel('502544','未设置开启/停止时间');
        return isValidate;
      }
    }
    if(publishSettings.dataUpperLimitEnabled.toString() === 'true') {
      if(!publishSettings.dataUpperLimitCount) {
        isValidate = false;
        this.error = getLabel('502545','未设置数据量上限');
        return isValidate;
      }
    }
    if(publishSettings.dailyTimeRangeEnabled.toString() === 'true') {
      if(!publishSettings.dailyStartTime || !publishSettings.dailyEndTime) {
        isValidate = false;
        this.error = getLabel('502546','未设置每日开启时段');
        return isValidate;
      }
    }
    if (!(wechatTypeInfo.serviceAppId && wechatTypeInfo.serviceSecret) &&
      !(!wechatTypeInfo.serviceAppId && !wechatTypeInfo.serviceSecret)
    ){
      isValidate = false;
      this.error = getLabel('504045', '微信服务号配置未填写完整');
      return isValidate;
    }
    if (!(wechatTypeInfo.wxworkAppId && wechatTypeInfo.wxworkSecret && wechatTypeInfo.wxworkAgentid) &&
      !(!wechatTypeInfo.wxworkAppId && !wechatTypeInfo.wxworkSecret && !wechatTypeInfo.wxworkAgentid)
    ) {
      isValidate = false;
      this.error = getLabel('504046', '企业微信配置未填写完整');
      return isValidate;
    }
    return isValidate;
  }

  tabClick(key){
    this.selectKey = key;
  }

  tabWxTypeClick(key){
    this.wxTypeSelectKey = key;
  }

  openPage(url) {
    window.open(url, "_blank");
  }

  onSetChange(key, value) {
    const { onSetChange } = this.store;
    onSetChange(key, value);
  }

  uploadImg(e){
    const value = e.target.value;
    if(value){
      const { uploadImg } = this.store;
      const data = new FormData();

      data.append('image',e.target.files[0]);
      uploadImg(data);
    }
  }

  setWxVisible(value){
    this.wxVisible = value;
  }

  setWxClick(){
    const { getWxTypeInfo } = this.store;
    
    getWxTypeInfo();
    this.setWxVisible(true);
  }

  renderQrcode(url) {
    return <div className="item">
      <div>
        <div className="qrcode">
          <WeaQrcode
            size={100}
            text={url}
          />
        </div>
        <p>{getLabel('502547','表单地址')}</p>
        <WeaInput
          value={url}
          disabled={true}
          style={{ width: "340px" }}
        />
        <CopyToClipboard text={url}
          onCopy={() => message.success(getLabel('502640','复制URL成功'))}
        >
          <Button>{getLabel('502548','复制网址')}</Button>
        </CopyToClipboard>
        <Button onClick={() => this.openPage(url)}>{getLabel('502549','直接打开')}</Button>
      </div>
    </div>;
  }

  renderFill(publishSettings, submissionAuthority, fillinFrequency) {
    return <div className="item">
      <div className="title">{getLabel('502550','填写规则')}</div>
      <div className="fill">
        <p>{getLabel('502551','谁能填')}</p>
        {
          submissionAuthority.map(v =>
            <div onClick={(e) => { e.preventDefault(); this.onSetChange('submissionAuthority', v.name) }} className={v.name === publishSettings.submissionAuthority ? 'active' : ''} style={{ display: "inline-block" }}>
              <WeaCheckbox
                id={v.name}
                value={v.name === publishSettings.submissionAuthority ? '1' : '0'}
                content={v.face}
              />
            </div>
          )
        }
        <p>{getLabel('502552','填几次')}</p>
        {
          fillinFrequency.map(v =>
            <div onClick={(e) => { e.preventDefault(); this.onSetChange('fillinFrequency', v.name) }} className={v.name === publishSettings.fillinFrequency ? 'active' : ''} style={{ display: "inline-block" }}>
              <WeaCheckbox
                id={v.name}
                value={v.name === publishSettings.fillinFrequency ? '1' : '0'}
                content={v.face}
              />
            </div>
          )
        }
      </div>
    </div>
  }

  renderForm(publishSettings) {
    return <div className="item">
      <div className="title">{getLabel('502553','表单开启/停止')}</div>
      <div className="form">
        <div className="fillOpen">
          <WeaCheckbox
            value={publishSettings.fillinEnabled ? '1' : '0'}
            display="switch"
            id="fillOpen"
            style={{ height: 20 }}
            onChange={value => this.onSetChange('fillinEnabled', value)}
          />
          <span>{publishSettings.fillinEnabled ? getLabel('502554','已开启') : getLabel('502555','已关闭')}</span>
        </div>
        <div className={publishSettings.fillinEnabled ? '' : 'hide'}>
          <div>
            <WeaCheckbox
              id="openTime"
              content={getLabel('502556','设定开启/停止时间')}
              value={publishSettings.timeRangeEnabled ? '1' : '0'}
              onChange={value => this.onSetChange('timeRangeEnabled', value)}
              helpfulTip={getLabel('502557','此属性用于指定填写表单的具体时间范围，填写者只有在这个时间范围内填写，方可正常提交表单') }
            />
            <div className={publishSettings.timeRangeEnabled ? 'form_item' : 'form_item hide'}>
              <p>{getLabel('502558','开始时间')}</p>
              <WeaDatePicker
                value={publishSettings.startTime ? publishSettings.startTime.split(' ')[0] : ''}
                formatPattern={2}
                style={{ width: 140 }}
                onChange={value => this.onSetChange('startDate', value)}
              />
              <WeaTimePicker
                value={publishSettings.startTime ? publishSettings.startTime.split(' ')[1] : ''}
                formatPattern={3}
                style={{ width: 100 }}
                onChange={value => this.onSetChange('startTime', value)}
              />
              <p>{getLabel('502559','停止时间')}</p>
              <WeaDatePicker
                value={publishSettings.endTime ? publishSettings.endTime.split(' ')[0] : ''}
                formatPattern={2}
                style={{ width: 140 }}
                onChange={value => this.onSetChange('endDate', value)}
              />
              <WeaTimePicker
                value={publishSettings.endTime ? publishSettings.endTime.split(' ')[1] : ''}
                formatPattern={3}
                style={{ width: 100 }}
                onChange={value => this.onSetChange('endTime', value)}
              />
            </div>
          </div>
          <div>
            <WeaCheckbox
              id="dataUpperLimit"
              value={publishSettings.dataUpperLimitEnabled ? '1' : '0'}
              content={getLabel('502587','设定数据量上限')}
              onChange={value => this.onSetChange('dataUpperLimitEnabled', value)}
              helpfulTip={getLabel('502588','此属性用于限制该表单总提交数据量。当数据量达到限额时，该表单将不能继续提交数据。')}
            />
            <div className={publishSettings.dataUpperLimitEnabled ? 'form_item' : 'form_item hide'} style={{ lineHeight: "30px" }}>
              {getLabel('502589','最多接受')}
                    <WeaInputNumber
                value={publishSettings.dataUpperLimitCount ? publishSettings.dataUpperLimitCount : ''}
                style={{ width: 80, margin: "0 4px" }}
                onChange={value => this.onSetChange('dataUpperLimitCount', value)}
              />
              {getLabel('502590','条数据')}
                  </div>
          </div>
          <div>
            <WeaCheckbox
              id="dailyTimeRang"
              value={publishSettings.dailyTimeRangeEnabled ? '1' : '0'}
              content={getLabel('502591','设定每日开启时段')}
              onChange={value => this.onSetChange('dailyTimeRangeEnabled', value)}
              helpfulTip={getLabel('502592','此属性用于限制表单每天允许填写的时间段，填写者只有在每天这个时间段内填写，方可正常提交数据。')}
            />
            <div className={publishSettings.dailyTimeRangeEnabled ? 'form_item' : 'form_item hide'}>
              <WeaTimeRangePicker
                value={[
                  publishSettings.dailyStartTime ? publishSettings.dailyStartTime : '',
                  publishSettings.dailyEndTime ? publishSettings.dailyEndTime : '',
                ]}
                onChange={value => { this.onSetChange('dailyStartTime', value[0]); this.onSetChange('dailyEndTime', value[1]); }}
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  }

  renderWeChat(url){
    const { imgList, diyImg, isLoading, setWechat, setWechatType, wechatSettings, wechatTypeInfo } = this.store;
    const { publishApp: externalApp } = this.props.edcAppStore;
    const { app } = this.props.edcAppDesignerStore;
    const { publishApp } = this.props;
    const currApp = publishApp ? publishApp : app ? app : externalApp;
    const labelLayout = {span:5};
    const inputLayout = {span:14};
    const serviceRequire = wechatTypeInfo.serviceAppId || wechatTypeInfo.serviceSecret;
    const wxworkRequire = wechatTypeInfo.wxworkAppId || wechatTypeInfo.wxworkSecret || wechatTypeInfo.wxworkAgentid;

    return <div className={`setting-wechat ${this.selectKey!=='2'?'hide':''}`}>
            <div className="clearfix">
              <div className="setting-left">
                <p>{getLabel('502596','微信分享标题')}</p>
                <WeaInput
                  value={wechatSettings.title}
                  placeholder={currApp.name}
                  onChange={value => {
                    setWechat('title', value)
                  }}
                />
                <p className="we-share-desc">{getLabel('502597','微信分享描述')}</p>
                <WeaTextarea
                  value={wechatSettings.description}
                  minRows={3}
                  maxRows={3}
                  onChange={value => {
                    setWechat('description', value)
                  }}
                />
              </div>
              <div className="setting-right">
                <p>{getLabel('502598','微信消息预览')}</p>
                <div className="mes-pre">
                  <img className="we-bg" src="/edc/images/wechat-message.png"></img>
                  <img className="pre-icon" src={wechatSettings.imgUrl}></img>
                  <span className="we-title">{wechatSettings.title?wechatSettings.title:currApp.name}</span>
                  <div className="we-desc">{wechatSettings.description}</div>
                </div>
              </div>
            </div>
            <div className="clearfix">
              <div className="setting-left">
                <p>{getLabel('502599','自定义图标')}</p>
                <img className="diy-icon" src={wechatSettings.imgUrl}></img>
                {isLoading && <Icon type="loading" />}
                <span className="upload-icon">
                    {getLabel('502600','上传自定义图标')}
                    <input type="file" onChange={this.uploadImg.bind(this)} accept=".jpg,.gif,.png,.jpeg"></input>
                </span>
                <div className="icon-wrap">
                  {
                    diyImg && 
                    <span 
                      className={`we-icon ${wechatSettings.imgUrl===diyImg?'active':''}`}
                      onClick={()=> setWechat('imgUrl', diyImg)}
                    >
                      <img className="diy-icon" src={diyImg}></img>
                    </span>
                  }
                  {
                    imgList.map(url => (
                      <span 
                        className={`we-icon ${wechatSettings.imgUrl===url?'active':''}`}
                        onClick={()=> setWechat('imgUrl', url)}
                      >
                        <img className="diy-icon" src={url}></img>
                      </span>
                    ))
                  }
                </div>
              </div>
              <div className="setting-right">
                <p>{getLabel('502601','朋友圈预览')}</p>
                <div className="friend-pre">
                  <img className="we-bg" src="/edc/images/wechat-friend.png"></img>
                  <img className="pre-icon" src={wechatSettings.imgUrl}></img>
                  <span className="we-title">{wechatSettings.title?wechatSettings.title:currApp.name}</span>
                </div>
              </div>
            </div>
            <div className="wechat-type clearfix">
                <p>{getLabel('504044', '集成配置')}</p>
                <Tabs defaultActiveKey={this.wxTypeSelectKey} onChange={this.tabWxTypeClick.bind(this)}>
                  <TabPane tab={getLabel('502620','微信服务号')} key="1">
                    <Row>
                      <Col {...labelLayout}><label>{getLabel('502609','服务号appid')}:</label></Col>
                      <Col {...inputLayout}>
                        <WeaInput 
                          className={serviceRequire && !wechatTypeInfo.serviceAppId && 'required '}
                          value={wechatTypeInfo.serviceAppId}
                          onChange={v => setWechatType('serviceAppId',v)}
                          placeholder={getLabel('502608', '请输入服务号appid')}
                        />
                      </Col>
                    </Row>
                    <Row>
                      <Col {...labelLayout}><label>{getLabel('502611','服务号secret')}:</label></Col>
                      <Col {...inputLayout}>
                        <WeaInput 
                          className={serviceRequire && !wechatTypeInfo.serviceSecret && 'required '}
                          value={wechatTypeInfo.serviceSecret}
                          onChange={v => setWechatType('serviceSecret',v)}
                          placeholder={getLabel('502610', '请输入服务号secret')}
                        />
                      </Col>
                    </Row>
                  </TabPane>
                  <TabPane tab={getLabel('502621','企业微信')} key="2">
                    <Row>
                      <Col {...labelLayout}><label>{getLabel('502613','企业号appid')}:</label></Col>
                      <Col {...inputLayout}>
                        <WeaInput 
                          className={wxworkRequire && !wechatTypeInfo.wxworkAppId && 'required '}
                          value={wechatTypeInfo.wxworkAppId}
                          onChange={v => setWechatType('wxworkAppId',v)}
                          placeholder={getLabel('502612', '请输入企业号appid')}
                        />
                      </Col>
                    </Row>
                    <Row>
                      <Col {...labelLayout}><label>{getLabel('502615','企业号secret')}:</label></Col>
                      <Col {...inputLayout}>
                        <WeaInput 
                          className={wxworkRequire && !wechatTypeInfo.wxworkSecret && 'required '}
                          value={wechatTypeInfo.wxworkSecret}
                          onChange={v => setWechatType('wxworkSecret',v)}
                          placeholder={getLabel('502614', '请输入企业号secret')}
                        />
                      </Col>
                    </Row>
                    <Row>
                      <Col {...labelLayout}><label>{getLabel('502617','企业号应用agentid')}:</label></Col>
                      <Col {...inputLayout}>
                        <WeaInput 
                          className={wxworkRequire && !wechatTypeInfo.wxworkAgentid && 'required '}
                          value={wechatTypeInfo.wxworkAgentid}
                          onChange={v => setWechatType('wxworkAgentid',v)}
                          placeholder={getLabel('502616', '请输入企业号应用agentid')}
                        />
                      </Col>
                    </Row>
                  </TabPane>
                </Tabs>
            </div>
            <div className='we-code clearfix'>
              <div className="we-qrcode">
                <WeaQrcode
                  size={100}
                  text={url}
                />
              </div>
              <div className="we-tip-desc">
                <p>{getLabel('502602','如果分享设置完成')}</p>
                <p>{getLabel('502603','你可以扫描二维码将表单分享至微信')}</p>
              </div>
            </div>
          </div>;
  }

  render() {
    const { visible, onCancel } = this.props;
    const { publishSettings, submissionAuthority, fillinFrequency,
       shortkey, isCreate,
    } = this.store;
    const buttons = [
      <Button type='primary' loading={this.saving} onClick={this.onOk} disabled={isCreate}>{getLabel('502604','保存设置')}</Button>,
      <Button type='ghost' onClick={onCancel}>{getLabel(31129,'取消')}</Button>
    ];
    const url = `${location.origin}/edc/formview/${shortkey}`;

    return (
      <WeaDialog
        title={getLabel('502605','发布')}
        className='publish'
        icon={"icon-coms02-Data-center"}
        iconBgcolor = "#1a57a0"
        hasScroll
        confirmLoading={true}
        visible={visible}
        buttons={buttons}
        onCancel={onCancel}
        style={{ width: 600, height: 700 }}
      >
        <div className="setting-content">
          <Tabs defaultActiveKey={this.selectKey} onChange={this.tabClick.bind(this)}>
            <TabPane tab={getLabel('502606','链接和二维码')} key="1">
            </TabPane>
            <TabPane tab={getLabel('502607','发布到微信')} key="2">
            </TabPane>
          </Tabs>
          <div className={`setting-url-code ${this.selectKey!=='1'?'hide':''}`}>
            {this.renderQrcode(url)}
            {this.renderFill(publishSettings, submissionAuthority, fillinFrequency)}
            {this.renderForm(publishSettings)}
          </div>
          {this.renderWeChat(url)}
        </div>
      </WeaDialog>
    );
  }
}
